<?php
namespace app\index\controller;

use Couchbase\Exception;
use think\Request;
use think\Controller;

class Index extends Base
{

    // 登录首页
    public function index()
    {
        $title = '首页';

        // 查询数据
        $data = \app\index\model\Index::order('id','asc')->select();
        return view('/index',['title' => $title,'data'=>$data]);
    }

    // 用户注册
    public function reg(){
        $title = "用户注册账户";
        return view('/register',['title' => $title]);
    }

    // 用户注册
    public function register(Request $request)
    {
        $data = $request->param();

        $rule = [
            'usernum' => 'require',
            'password'=>'require|confirm'
        ];

        $msg = [
            'usernum.require' => '用户名不得为空',
            'password.confirm' => '两次密码输入不一致'
        ];

        $validate = new \think\Validate($rule, $msg);

        // 判断是否存在
        if (!$validate->check($data)) {

            $error = $validate->getError();

            return $this->error($error);
        }
        $data['password'] = md5passeword($data['password']);
        $user = \app\Index\model\Index::where('usernum',$data['usernum'])->find();

        if($user){
            return $this->error("用户已经注册，请更换账号","/index/index/reg");
        }

        \app\Index\model\Index::create($data,true);

        return $this->success("用户注册成功，","/index/index/index");
    }

    // 用户修改
    public function edit(int $id){
        if(empty($id)){
            $this->error("输入不正确",'/index/index/index');
        }
        $data = \app\index\model\Index::find($id);
        $title = "修改页面";
        return view('/edit',['data'=>$data,'title'=>$title]);
    }

    // 修改成功页面
    public function update(Request $request,int $id){
        $data = $request->param();
        $rule = [
            'usernum' => 'require',
            'username' => 'require',
            'password' => 'require'
        ];
        $msg = [
            'usernum.require' => '用户账号不能为空',
            'username.require' => '用户名不能为空',
            'password.require' => '密码不能为空'
        ];

        $validate = new \think\Validate($rule,$msg);

        if(!$validate->check($data)){
            $error = $validate->getError();
            return $this->error($error);
        }
        $data['password'] = md5passeword($data['password']);
        \app\index\model\Index::where('id',$id)->update($data);

        return $this->success('用户修改成功','index/index/index');
    }

    // 用户删除
    public function delete(int $id)
    {
        \app\index\model\Index::where('id',$id)->delete();

        return $this->success("删除成功",'/index/index/index');
    }


}
